<template>
    <a-modal
        :title="title"
        centered
        :width="980"
        :maskClosable="false"
        :destroyOnClose="true"
        :visible="visible"
        :confirmLoading="confirmLoading"
        @ok="handleSubmit"
        @cancel="cancel"
    >
        <a-spin :spinning="confirmLoading">
            <a-form :model="form" ref="formRef" :rules="formRules">
                <a-divider orientation="left">基本信息</a-divider>
                <a-row :gutter="24">
                    <a-col :md="12" :sm="24">
                        <a-form-item
                            label="账号"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                            has-feedback
                            name="account"
                            :rules="[{ required: true, min: 5, message: '请输入至少五个字符的账号！' }]"
                        >
                            <a-input :maxLength="35" placeholder="请输入账号" v-model:value="form.account" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="12" :sm="24">
                        <a-form-item
                            label="姓名"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                            has-feedback
                            name="name"
                            :rules="[{ required: true, message: '请输入姓名！' }]"
                        >
                            <a-input :maxLength="35" placeholder="请输入姓名" v-model:value="form.name" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24" v-if="add">
                    <a-col :md="12" :sm="24">
                        <a-form-item
                            label="密码"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                            has-feedback
                            name="password"
                            :rules="[{ required: true, message: '请输入密码！' }, { validator: validatePass }]"
                        >
                            <a-input
                                placeholder="请输入密码"
                                type="password"
                                :maxLength="35"
                                v-model:value="form.password"
                                autoComplete="new-password"
                            />
                        </a-form-item>
                    </a-col>
                    <a-col :md="12" :sm="24">
                        <a-form-item
                            label="重复密码"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                            has-feedback
                            name="confirm"
                            :rules="[{ required: true, message: '请再次输入密码！' }, { validator: validatePass2 }]"
                        >
                            <a-input placeholder="请再次输入密码" type="password" :maxLength="35" autocomplete="off" v-model:value="form.confirm" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="12" :sm="24">
                        <a-form-item label="昵称" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                            <a-input :maxLength="35" placeholder="请输入昵称" v-model:value="form.nickName" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="12" :sm="24">
                        <a-form-item label="生日" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                            <a-date-picker
                                :disabled-date="disabledDate"
                                placeholder="请选择生日"
                                style="width: 100%"
                                v-model:value="form.birthday"
                                valueFormat="YYYY-MM-DD"
                            />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="12" :sm="24">
                        <a-form-item
                            label="性别"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                            name="sex"
                            :rules="[{ required: true, message: '请选择性别！', type: 'number', trigger: 'change' }]"
                        >
                            <a-radio-group v-model:value="form.sex">
                                <a-radio :value="1">男</a-radio>
                                <a-radio :value="2">女</a-radio>
                            </a-radio-group>
                        </a-form-item>
                    </a-col>
                    <a-col :md="12" :sm="24">
                        <a-form-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol" name="email" :rules="formRules.email">
                            <a-input placeholder="请输入邮箱" v-model:value="form.email" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="12" :sm="24">
                        <a-form-item label="手机号" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback name="phone" :rules="formRules.phone">
                            <a-input placeholder="请输入手机号" v-model:value="form.phone" />
                        </a-form-item>
                    </a-col>
                    <a-col :md="12" :sm="24">
                        <a-form-item label="电话" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                            <a-input :maxLength="15" placeholder="请输入电话" v-model:value="form.tel" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-divider orientation="left">员工信息</a-divider>
                <a-row :gutter="24">
                    <a-col :md="12" :sm="24">
                        <a-form-item
                            label="机构"
                            :labelCol="labelCol"
                            :wrapperCol="wrapperCol"
                            has-feedback
                            :name="['sysEmpParam', 'orgId']"
                            :rules="{ required: true, message: '请选择机构！' }"
                        >
                            <a-tree-select
                                placeholder="请选择机构"
                                v-model:value="form.sysEmpParam.orgId"
                                style="width: 100%"
                                :dropdownStyle="{ maxHeight: '300px', overflow: 'auto' }"
                                :treeData="treeData"
                                treeDefaultExpandAll
                                @change="initrOrgName"
                            >
                                <template #title="{ id }">
                                    <span>{{ id }}</span>
                                </template>
                            </a-tree-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md="12" :sm="24">
                        <a-form-item label="工号" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback>
                            <a-input :maxLength="35" placeholder="请输入工号" v-model:value="form.sysEmpParam.jobNum" />
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <a-form-item
                            label="职位信息"
                            :labelCol="labelCol_JG"
                            :wrapperCol="wrapperCol_JG"
                            has-feedback
                            :name="['sysEmpParam', 'posIdList']"
                            :rules="{ required: true, message: '请选择职位信息！', type: 'array' }"
                        >
                            <a-select mode="multiple" style="width: 100%" placeholder="请选择职位信息" v-model:value="form.sysEmpParam.posIdList">
                                <a-select-option v-for="(item, index) in posList" :key="index" :value="item.id">{{ item.name }}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row :gutter="24">
                    <a-col :md="24" :sm="24">
                        <a-form-item label="附属信息:" :labelCol="labelCol_JG" :wrapperCol="wrapperCol_JG">
                            <a-table :pagination="false" :columns="columns" :dataSource="form.sysEmpParam.extIds" :rowKey="(record) => record.key">
                                <template #orgId="{ record }">
                                    <a-tree-select
                                        :treeData="treeData"
                                        style="width: 100%"
                                        placeholder="请选择附属机构"
                                        treeDefaultExpandAll
                                        v-model:value="record.orgId"
                                    >
                                    </a-tree-select>
                                </template>
                                <template #posId="{ record }">
                                    <a-select style="width: 100%" placeholder="请选择附属职位" v-model:value="record.posId" has-feedback>
                                        <a-select-option v-for="(item, indexs) in posList" :key="indexs" :value="item.id">{{
                                            item.name
                                        }}</a-select-option>
                                    </a-select>
                                </template>
                                <template #operation="{ record }">
                                    <a @click="remove(record.key)">删除</a>
                                </template>
                            </a-table>
                            <a-button style="width: 100%; margin-top: 16px; margin-bottom: 8px" type="dashed" @click="newMember">
                                <template #icon>
                                    <PlusOutlined />
                                </template>
                                增行</a-button
                            >
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-spin>
    </a-modal>
</template>

<script lang='ts'>
import { defineComponent, PropType, reactive, toRefs, ref, computed, watch, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from '@/store'
import { formRules } from '@/utils/validator'
import { RuleObject, ValidateErrorEntity } from 'ant-design-vue/es/form/interface'
import { getOrgList, sysPosList, sysUserAdd, sysUserEdit } from '@/api/system/user'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { uniqueId } from 'lodash'
interface extIdsType {
    key: string
    orgId: unknown
    posId: unknown
}
export default defineComponent({
    name: 'operationFrom',
    components: {},
    props: {
        treeData: {
            type: Array,
            default: []
        }
    },
    emits: ['refresh'],
    setup(props, ctx) {
        const formRef = ref<any>(null)
        const router = useRouter()
        const store = useStore()
        const state = reactive({
            labelCol: {
                xs: { span: 24 },
                sm: { span: 6 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 }
            },
            // 机构行样式
            labelCol_JG: {
                xs: { span: 24 },
                sm: { span: 3 }
            },
            wrapperCol_JG: {
                xs: { span: 24 },
                sm: { span: 20 }
            },
            count: 1,
            columns: [
                {
                    title: '附属机构',
                    dataIndex: 'orgId',
                    width: '45%',
                    slots: { customRender: 'orgId' }
                },
                {
                    title: '附属岗位',
                    dataIndex: 'posId',
                    width: '45%',
                    slots: { customRender: 'posId' }
                },
                {
                    title: '操作',
                    key: 'action',
                    slots: { customRender: 'operation' }
                }
            ],
            add: false,
            visible: false,
            confirmLoading: false,
            orgList: [] as any,
            posList: [],
            detailData: {} as any,
            sysEmpParamExtList: [],
            memberLoading: false,
            title: '',
            id: '',
            form: {
                account: '',
                confirm: '',
                name: '',
                nickName: '',
                password: '',
                phone: '',
                email: '',
                birthday: '',
                tel: '',
                sex: 1,
                sysEmpParam: {
                    jobNum: '',
                    extIds: [] as extIdsType[],
                    orgId: undefined,
                    orgName: '',
                    posIdList: [] as string[]
                }
            },
            birthdayString: [] as string[]
        })
        /**详情监听 */
        watch(
            () => state.detailData,
            (v) => {
                var posIdList = [] as string[]
                var extIds = [] as extIdsType[]

                v.sysEmpInfo.positions.map((v) => {
                    posIdList.push(v.posId)
                })
                v.sysEmpInfo.extOrgPos.map((vv, i) => {
                    extIds.push({
                        key: uniqueId(),
                        orgId: vv.orgId,
                        posId: vv.posId
                    })
                })
                state.form = {
                    account: v.account,
                    name: v.name,
                    nickName: v.nickName,
                    confirm: '',
                    password: '',
                    tel: v.tel,
                    phone: v.phone,
                    sex: v.sex,
                    email: v.email,
                    birthday: v.birthday,
                    sysEmpParam: {
                        jobNum: v.sysEmpInfo.jobNum,
                        extIds: extIds,
                        orgId: v.sysEmpInfo.orgId,
                        orgName: v.sysEmpInfo.orgName,
                        posIdList: posIdList
                    }
                }
            }
        )
        onMounted(() => {
            sysPosList().then((res) => {
                state.posList = res
            })
            // getOrgList().then((res) => {
            //   state.orgList = res
            // })
        })
        function handleSubmit() {
            state.confirmLoading = true
            formRef.value
                .validate()
                .then(() => {
                    state.form.sysEmpParam.extIds = state.form.sysEmpParam.extIds.filter((v) => v.orgId && v.posId)
                    if (state.title == '新增用户') {
                        sysUserAdd(state.form)
                            .then((res) => {
                                message.success('新增成功')
                                state.confirmLoading = false
                                state.visible = false
                                ctx.emit('refresh')
                            })
                            .catch((err) => {
                                state.confirmLoading = false
                            })
                    } else if (state.title == '编辑用户') {
                        sysUserEdit({ ...state.form, id: state.id })
                            .then((res) => {
                                message.success('编辑成功')
                                state.confirmLoading = false
                                state.visible = false
                                ctx.emit('refresh')
                            })
                            .catch((err) => {
                                state.confirmLoading = false
                            })
                    }
                })
                .catch((err) => {
                    state.confirmLoading = false
                    console.log('nopass', err)
                })
        }
        /**
         * 重置表单
         */
        function resetForm() {
            state.form = {
                account: '',
                name: '',
                nickName: '',
                confirm: '',
                password: '',
                tel: '',
                phone: '',
                email: '',
                birthday: '',
                sex: 1,
                sysEmpParam: {
                    jobNum: '',
                    extIds: [] as extIdsType[],
                    orgId: undefined,
                    orgName: '',
                    posIdList: []
                }
            }
        }
        /**
         * 退出
         */
        const cancel = () => {
            resetForm()
            //   formRef.value.resetFields()
            state.visible = false
        }
        /**
         * 禁用日期
         */
        const disabledDate = (current) => {
            return current && current > dayjs().endOf('day') //当天之前的不可选，包括当天
            // return current < dayjs().subtract(1, 'day')// 当天之前的不可选，不包括当天
        }

        /**
         * 增行
         */
        function newMember() {
            let data = state.form.sysEmpParam.extIds
            let length = data.length
            data.push({
                key: uniqueId(),
                orgId: undefined,
                posId: undefined
            })
        }
        /**
         * 删除
         */
        function remove(key) {
            state.form.sysEmpParam.extIds.splice(
                state.form.sysEmpParam.extIds.findIndex((v) => v.key == key),
                1
            )
        }
        /**
         * handleChange
         */
        function handleChange() {}
        /**
         * 选择树机构，初始化机构名称于表单中
         */
        function initrOrgName(value, label, extra) {
            state.form.sysEmpParam.orgId = value
            state.form.sysEmpParam.orgName = label[0]
        }
        const validatePass = async (rule: RuleObject, value: string) => {
            if (value === '') {
                return Promise.reject('请输入密码')
            } else {
                if (state.form.confirm !== '') {
                    formRef.value.validateField('checkPass')
                }
                return Promise.resolve()
            }
        }
        const validatePass2 = async (rule: RuleObject, value: string) => {
            if (value === '') {
                return Promise.reject('请再次输入密码')
            } else if (value !== state.form.password) {
                return Promise.reject('请确认两次输入密码的一致性！')
            } else {
                return Promise.resolve()
            }
        }
        return {
            ...toRefs(state),
            props,
            formRef,
            formRules,
            handleSubmit,
            initrOrgName,
            validatePass,
            validatePass2,
            handleChange,
            disabledDate,
            cancel,
            remove,
            newMember
        }
    }
})
</script>
